<?php

/**
 * invoices actions.
 *
 * @package    corpon
 * @subpackage invoices
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class invoicesActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    $this->invoices = new Invoice();

    $this->pager = new sfDoctrinePager('Invoice',sfConfig::get('app_max_invoices'));
    $this->pager->setQuery($this->invoices->getInvoicesQuery());
    $this->pager->setPage($request->getParameter('page', 1));
    $this->pager->init();

    $this->invoices = $this->pager->getResults();
  }

  public function executeMyOrders(sfWebRequest $request)
  {
    $this->invoices = new Invoice();

    $this->pager = new sfDoctrinePager('Invoice',sfConfig::get('app_max_invoices'));
    $this->pager->setQuery($this->invoices->getUserOrdersQuery($this->getUser()->getAttribute('id_user')));
    $this->pager->setPage($request->getParameter('page', 1));
    $this->pager->init();

    $this->invoices = $this->pager->getResults();
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->invoice = Doctrine_Core::getTable('Invoice')->find(array($request->getParameter('id_invoice')));

    $this->forward404Unless($this->invoice);

    $this->forward404Unless($this->getUser()->hasCredential('Admin') ||
            ($this->getUser()->isAuthenticated() && $this->getUser()->getAttribute('id_user')==$this->invoice->getIdUser()));

    $this->products = Doctrine_Core::getTable('InvoiceProducts')->findByIdInvoice($this->invoice->getIdInvoice());
    
  }

  public function executePrint(sfWebRequest $request)
  {
    $this->invoice = Doctrine_Core::getTable('Invoice')->find(array($request->getParameter('id_invoice')));

    $this->forward404Unless($this->invoice);

    $this->forward404Unless($this->getUser()->hasCredential('Admin') ||
            ($this->getUser()->isAuthenticated() && $this->getUser()->getAttribute('id_user')==$this->invoice->getIdUser()));

    $this->products = Doctrine_Core::getTable('InvoiceProducts')->findByIdInvoice($this->invoice->getIdInvoice());

  }

  public function executeError(sfWebRequest $request)
  {
    $this->invoice = Doctrine_Core::getTable('Invoice')->find(array($request->getParameter('id_invoice')));

    $this->forward404Unless($this->invoice);

    $this->forward404Unless($this->getUser()->hasCredential('Admin') ||
            ($this->getUser()->isAuthenticated() && $this->getUser()->getAttribute('id_user')==$this->invoice->getIdUser()));
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new InvoiceForm();
                    $today = date('Y-m-d');
      $this->products = Doctrine::getTable('Product')
                ->createQuery('p')
                ->select('p.*')
                ->where('p.status = 1')
                ->andWhere('p.start_date <= ?',$today)
                ->andWhere('p.end_date >= ?',$today)
                ->orderBy('Rand()')
                ->limit('4')
                ->execute();
  }

  public function executeCheckout(sfWebRequest $request)
  {
    $invoice = new Invoice();
    $invoice->setInvoiceAmount($request->getParameter('amount'));
    $invoice->setShippingAmount($request->getParameter('shipping'));

    //$this->form = new InvoiceForm();
    $this->amount = $request->getParameter('amount');
    $this->shipping = $request->getParameter('shipping');
    $this->products = $request->getParameter('product');
    
    $this->form = new InvoiceForm($invoice);
  }

  public function executeCheckoutCredit(sfWebRequest $request)
  {
    $invoice = new Invoice();
    $invoice->setInvoiceAmount($request->getParameter('amount'));
    $invoice->setShippingAmount($request->getParameter('shipping'));

    $this->has_invoice = false;

    if ($request->getParameter('id_invoice')) :
       $this->invoice = Doctrine_Core::getTable('Invoice')->find($request->getParameter('id_invoice'));
       if ($this->invoice) :
        $invoice->setBillingAddress($this->invoice->getBillingAddress());
        $invoice->setBillingCity($this->invoice->getBillingCity());
        $invoice->setBillingCompany($this->invoice->getBillingCompany());
        $invoice->setBillingEmail($this->invoice->getBillingEmail());
        $invoice->setBillingFax($this->invoice->getBillingFax());
        $invoice->setBillingLastName($this->invoice->getBillingLastName());
        $invoice->setBillingName($this->invoice->getBillingName());
        $invoice->setBillingPhone($this->invoice->getBillingPhone());
        $invoice->setBillingState($this->invoice->getBillingState());
        $invoice->setBillingZip($this->invoice->getBillingZip());
        $invoice->setShippingAddress($this->invoice->getShippingAddress());
        $invoice->setShippingAmount($this->invoice->getShippingAmount());
        $invoice->setShippingCity($this->invoice->getShippingCity());
        $invoice->setShippingCompany($this->invoice->getShippingCompany());
        $invoice->setShippingLastName($this->invoice->getShippingLastName());
        $invoice->setShippingName($this->invoice->getShippingName());
        $invoice->setShippingState($this->invoice->getShippingState());
        $invoice->setShippingZip($this->invoice->getShippingZip());
       endif;
    endif;

    //$this->form = new InvoiceForm();
    $this->amount = $request->getParameter('amount');
    $this->shipping = $request->getParameter('shipping');
    $this->products = $request->getParameter('product');

    $this->form = new InvoiceForm($invoice);
  }

   
  public function executeConfirmation(sfWebRequest $request)
  {


  }

  public function executeConfirmationCredit(sfWebRequest $request)
  {
    /**
    * Get required parameters from the web form for the request
    */
    $this->invnum = urlencode($request->getParameter('invnum'));
    $this->paymentType = urlencode($request->getParameter('paymentType'));
    $this->firstName =urlencode($request->getParameter('firstName'));
    $this->lastName =urlencode($request->getParameter('lastName'));
    $this->creditCardType =urlencode($request->getParameter('creditCardType'));
    $this->creditCardNumber = urlencode($request->getParameter('creditCardNumber'));
    $this->expDateMonth =urlencode( $request->getParameter('expDateMonth'));

    // Month must be padded with leading zero
    $this->padDateMonth = str_pad($this->expDateMonth, 2, '0', STR_PAD_LEFT);

    $this->expDateYear =urlencode($request->getParameter('expDateYear'));
    $this->cvv2 = urlencode($request->getParameter('cvv2Number'));
    $this->street = urlencode($request->getParameter('address1'));
    $this->city = urlencode($request->getParameter('city'));
    $this->state =urlencode($request->getParameter('state'));
    $this->zip = urlencode($request->getParameter('zip'));
    $this->amount = urlencode($request->getParameter('amount'));
    $this->email = urlencode($request->getParameter('email'));
    $this->phone = urlencode($request->getParameter('phone'));
    $this->tax = urlencode($request->getParameter('tax'));
    $this->shipping = urlencode($request->getParameter('shipping'));

    $this->shipping_address = urlencode($request->getParameter('shipping_address'));
    $this->shipping_city = urlencode($request->getParameter('shipping_city'));
    $this->shipping_state =urlencode($request->getParameter('shipping_state'));
    $this->shipping_zip = urlencode($request->getParameter('shipping_zip'));
    //$currencyCode=urlencode($_POST['currency']);
    $this->currencyCode="USD";

    /********************************************
	Payflow API Module

	Defines all the global variables and the wrapper functions
	********************************************/
	$this->PROXY_HOST = '127.0.0.1';
	$this->PROXY_PORT = '808';

	$this->Env = "live";

	//'------------------------------------
	//' Payflow API Credentials
	//'------------------------------------
	$this->API_User="docuimage";
	//' Fill in the API_Password variable yourself, the wizard will not do this automatically
	$this->API_Password="technology01";
	$this->API_Vendor="docuimage";
	$this->API_Partner="PayPal";

	// BN Code
	$this->sBNCode = "PF-CCWizard";

  }

  public function executeApiError(sfWebRequest $request)
  {


  }
  
  public function executeCancel(sfWebRequest $request)
  {


  }
  
  public function executeRedirectToAuth(sfWebRequest $request)
  {
    $this->invoice = Doctrine_Core::getTable('Invoice')->find(array($request->getParameter('id_invoice')));

    $this->products = Doctrine_Core::getTable('InvoiceProducts')->findByIdInvoice(array($this->invoice->getIdInvoice()));

    //Authorize's account info
    $this->loginID		= "5sfGqp6F8U";
    $this->transactionKey = "6U993ehZjN652wat";

    //Account configuration
    $this->description 	= "Shopping Cart";
    $this->testMode	= "false";
    $this->url		= "https://test.authorize.net/gateway/transact.dll";
  }

  public function executeRedirectCredit(sfWebRequest $request)
  {
    $this->invoice = Doctrine_Core::getTable('Invoice')->find(array($request->getParameter('id_invoice')));

    $this->products = Doctrine_Core::getTable('InvoiceProducts')->findByIdInvoice(array($this->invoice->getIdInvoice()));

    //Authorize's account info
    $this->loginID		= "5sfGqp6F8U";
    $this->transactionKey = "6U993ehZjN652wat";

    //Account configuration
    $this->description 	= "Shopping Cart";
    $this->testMode	= "false";
    $this->url		= "https://test.authorize.net/gateway/transact.dll";
  }

  public function executeInvoice(sfWebRequest $request)
  {

  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new InvoiceForm();

    $this->processForm($request, $this->form);

    switch ($request->getParameter('checkout')) :
        case 1:
            $this->setTemplate('checkout');
            break;
        case 2:
            $this->setTemplate('checkoutCredit');
            break;
        default:
            $this->setTemplate('new');
            break;
    endswitch;

  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($invoice = Doctrine_Core::getTable('Invoice')->find(array($request->getParameter('id_invoice'))), sprintf('Object invoice does not exist (%s).', $request->getParameter('id_invoice')));
    $this->form = new InvoiceForm($invoice);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($invoice = Doctrine_Core::getTable('Invoice')->find(array($request->getParameter('id_invoice'))), sprintf('Object invoice does not exist (%s).', $request->getParameter('id_invoice')));
    $this->form = new InvoiceForm($invoice);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($invoice = Doctrine_Core::getTable('Invoice')->find(array($request->getParameter('id_invoice'))), sprintf('Object invoice does not exist (%s).', $request->getParameter('id_invoice')));
    $invoice->delete();

    $this->redirect('invoices/index');
  }

  public function executeReorder(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    
    $this->invoice = Doctrine_Core::getTable('Invoice')->find(array($request->getParameter('id_invoice')));

    $this->forward404Unless($this->invoice);

    $this->forward404Unless($this->getUser()->hasCredential('Admin') ||
            ($this->getUser()->isAuthenticated() && $this->getUser()->getAttribute('id_user')==$this->invoice->getIdUser()));

    $this->products = Doctrine_Core::getTable('InvoiceProducts')->findByIdInvoice($this->invoice->getIdInvoice());

    /*$invoice = new Invoice();


    $invoice->setBillingAddress($this->invoice->getBillingAddress());
    $invoice->setBillingCity($this->invoice->getBillingCity());
    $invoice->setBillingCompany($this->invoice->getBillingCompany());
    $invoice->setBillingEmail($this->invoice->getBillingEmail());
    $invoice->setBillingFax($this->invoice->getBillingFax());
    $invoice->setBillingLastName($this->invoice->getBillingLastName());
    $invoice->setBillingName($this->invoice->getBillingName());
    $invoice->setBillingPhone($this->invoice->getBillingPhone());
    $invoice->setBillingState($this->invoice->getBillingState());
    $invoice->setBillingZip($this->invoice->getBillingZip());
    $invoice->setIdUser($this->getUser()->getAttribute('id_user'));
    $invoice->setInvoiceAmount($this->invoice->getInvoiceAmount());
    $invoice->setShippingAddress($this->invoice->getShippingAddress());
    $invoice->setShippingAmount($this->invoice->getShippingAmount());
    $invoice->setShippingCity($this->invoice->getShippingCity());
    $invoice->setShippingCompany($this->invoice->getShippingCompany());
    $invoice->setShippingLastName($this->invoice->getShippingLastName());
    $invoice->setShippingName($this->invoice->getShippingName());
    $invoice->setShippingState($this->invoice->getShippingState());
    $invoice->setShippingZip($this->invoice->getShippingZip());
    $invoice->setTaxAmount($this->invoice->getTaxAmount());

    date_default_timezone_set('America/Chicago');

    $invoice->setCreatedAt(date('Y-m-d H:i:s', time()));
    $invoice->save();

        foreach($this->products as $product) :
          $invoice_products = new InvoiceProducts();
          $invoice_products->setIdInvoice($invoice->getIdInvoice());
          $invoice_products->setProductQuantity($product->getProductQuantity());
          $invoice_products->setIdProduct($product->getIdProduct());
          $invoice_products->save();
        endforeach;

        $this->redirect('redirect_credit',$invoice);
     *
     */
    $cart = array();
    
    $this->getUser()->setAttribute('cart', $cart);

    foreach($this->products as $product) :

        $cart[md5($product->Product->getIdProduct())] = array('id' => md5($product->Product->getIdProduct()),
                                  'quantity' => $product->getProductQuantity(),
                                  'product_name' => $product->Product->getName(),
                                  'product_description' => $product->Product->getDescription(),
                                  'product_price' => $product->Product->getDiscountedPrice(),
                                  'id_product' => $product->Product->getIdProduct(),
                                  'shipping_price' => '');

        $this->getUser()->setAttribute('cart', $cart);

        endforeach;

    if ($request->getParameter('company')) :
       $this->redirect('/shoppingCart/'.$request->getParameter('company').'?id_invoice='.$this->invoice->getIdInvoice());
    else :
       $this->redirect('products/shoppingCart');
    endif;

  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $invoice = $form->save();

      if ($request->getParameter('checkout')) :

        $products = $request->getParameter('product');
        foreach($products as $array => $product_param) :
          $product = explode(',', $product_param);
          $product_quantity = $product[1];
          $product_id = $product[0];
          
          $invoice_products = new InvoiceProducts();
          $invoice_products->setIdInvoice($invoice->getIdInvoice());
          $invoice_products->setProductQuantity($product_quantity);
          $invoice_products->setIdProduct($product_id);
          $invoice_products->save();
        endforeach;

        switch ($request->getParameter('checkout')) :
          case 1:
            $this->redirect('redirect_authorize',$invoice);
            break;
          case 2:
            $this->redirect('redirect_credit',$invoice);
            break;
        endswitch;

      endif;

      $this->redirect('invoices/edit?id_invoice='.$invoice->getIdInvoice());
    }
  }
}
